package JavaSE.TCPUDPLearning.OneToOne;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
// 接收端
public class ReceiveTaskImpl implements Runnable {
    DatagramSocket socket;
    String IPAddress;
    int port;

    public ReceiveTaskImpl(DatagramSocket socket, String IPAddress, int port) {
        this.socket = socket;
        this.IPAddress = IPAddress;
        this.port = port;
    }

    public void receiveMessage() throws IOException {
        // 接收 接收端发送的数据
        // 创建socket对象
        // 创建用于接收的数据报包
        while(true) {
            byte[] bytes = new byte[1024];
            // 创建数据报包
            DatagramPacket receivePacket = new DatagramPacket(bytes, 0, bytes.length);
            // receive方法接收
            socket.receive(receivePacket);
            // 解析数据报包
            byte[] data = receivePacket.getData();
            // 获取缓冲区中的length 和offset
            int length = receivePacket.getLength();
            int offset = receivePacket.getOffset();
            String message = new String(data,offset,length);
            System.out.println(message);
            if(message.equals("88")) {
                break;
            }
        }
        socket.close();
    }
    @Override
    public void run() {
        try {
            receiveMessage();
        } catch (IOException e) {
            System.out.println("已关闭");
        }
    }
}
